<template>
  <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="dialogVisible">
    <el-form ref="formRef" class="p-3" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="角色编码" prop="roleCode">
        <el-input :disabled="isEdit" v-model="form.roleCode" placeholder="请输入角色编码"></el-input>
      </el-form-item>
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="form.roleName" placeholder="请输入角色名称"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          type="textarea"
          :rows="2"
          maxlength="255"
          show-word-limit
          v-model="form.remark"
          placeholder="请输入备注"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, defineEmits } from "vue";
import { ElMessage } from "element-plus";
import { getRoleById, addRole, updateRole } from "@/api/modules/role";

const dialogVisible = ref(false);
const formRef = ref(null);
const form = ref({
  roleCode: "",
  roleName: "",
  remark: ""
});
const rules = {
  roleCode: [{ required: true, message: "请输入角色编码", trigger: "blur" }],
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }]
};
const isEdit = ref(false);
const emit = defineEmits(["cancel", "confirm"]);

const handleCancel = () => {
  emit("cancel");
  dialogVisible.value = false;
};

const handleConfirm = () => {
  formRef.value.validate(valid => {
    if (valid) {
      const apiCall = isEdit.value ? updateRole : addRole;
      apiCall(form.value).then(res => {
        if (res.code === 200) {
          emit("confirm");
          ElMessage.success(isEdit.value ? "编辑成功！" : "添加成功！");
          dialogVisible.value = false;
          formRef.value.resetFields();
        }
      });
    }
  });
};
const openDialog = id => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  dialogVisible.value = true;
  if (id) {
    isEdit.value = true;
    getRoleById(id).then(res => {
      form.value = res.data;
    });
  } else {
    isEdit.value = false;
    form.value = {
      roleCode: "",
      roleName: "",
      remark: ""
    };
  }
};
defineExpose({
  openDialog
});
</script>
